<template>
	<view class="shop-container">
		<!-- 头部区域 -->
		<view class="header-section">
			<view class="status_bar" style="height: var(--status-bar-height); width: 100%;"></view>
			<view class="header-content">
				<view class="header-title">
					<tn-icon name="cart-fill" size="36" color="#ffffff" />
					<text class="title-text">购物车</text>
				</view>
				<view class="cart-badge" v-if="shoppingCartData.length > 0">
					{{ shoppingCartData.length }}家店铺
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="shoppingCartData.length === 0">
			<view class="empty-content">
				<view class="empty-icon">
					<tn-icon name="cart" size="120" color="#e5e7eb" />
				</view>
				<view class="empty-text">
					<text class="empty-title">购物车还是空的</text>
					<text class="empty-subtitle">快去挑选心仪的商品吧～</text>
				</view>
				<view class="empty-action">
					<tn-button 
						class="shop-now-btn" 
						shape="round" 
						@click="doTurnAround"
						:custom-style="shopNowBtnStyle"
					>
						<tn-icon name="shop" size="28" color="#ffffff" />
						<text class="btn-text">去逛逛</text>
					</tn-button>
				</view>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="cart-list" v-if="shoppingCartData.length > 0">
			<view class="merchant-card" v-for="(item, index) in shoppingCartData" :key="index">
				<!-- 商家头部 -->
				<view class="merchant-header" @click="toNavigate(item)">
					<view class="merchant-info">
						<view class="merchant-icon">
							<tn-icon name="shop" size="28" :color="mainColor" />
						</view>
						<view class="merchant-details">
							<text class="merchant-name">{{ item.businessname }}</text>
							<text class="merchant-stats">{{ item.details.length }}件商品</text>
						</view>
					</view>
					<view class="merchant-actions">
						<view class="total-price">
							<text class="currency">¥</text>
							<text class="amount">{{ item.taxamount }}</text>
						</view>
						<view class="action-buttons">
							<view class="delete-btn" @click.stop="doDelShopping(item.businessid, index)">
								<tn-icon name="delete" size="24" color="#ff4757" />
							</view>
							<view class="arrow-btn">
								<tn-icon name="right" size="20" color="#999" />
							</view>
						</view>
					</view>
				</view>

				<!-- 商品图片网格 -->
				<view class="products-grid" @click="toNavigate(item)">
					<view class="grid-container">
						<view 
							v-for="(itemDetails, indexDetails) in item.details.slice(0, 10)" 
							:key="indexDetails"
							class="product-item"
						>
							<image 
								:src="itemDetails.imgurl" 
								class="product-image"
								mode="aspectFill" 
								@error="imgerror(index, indexDetails)"
							/>
						</view>
						<!-- 显示更多商品数量 -->
						<view class="more-products" v-if="item.details.length > 10">
							<text class="more-text">+{{ item.details.length - 10 }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部安全区域 -->
		<view class="safe-area-bottom"></view>
	</view>

	<view ref="rootElement"></view>
	<tn-modal ref="modalRef" :zIndex="zIndex"/>
</template>

<script setup>
	import { ref, reactive, onMounted, computed } from 'vue'
	import { postCall } from '@/api/index.js'
	import { EventBus } from '@/mitt/EventBus.js';
	import { toastMessage } from '@/utils/toast.js';
	import { getCSSVariable } from '@/utils/platform.js';
	import Big from 'big.js';
	import { userAllDataStore } from '@/stores'

	const store = userAllDataStore();
	const zIndex = ref(99999);
	const procName = "PROC_APP_DO_SHOPPING";
	const modal = ref(false);
	let noneGoodsImageUrl = ref("");
	const rootElement = ref(null);
	const mainColor = ref('#6bb7ec');

	// 按钮样式
	const shopNowBtnStyle = {
		backgroundColor: 'var(--tn-color-primary)',
		border: 'none',
		boxShadow: '0 8px 20px rgba(var(--tn-color-primary-rgb), 0.3)',
		height: '88rpx',
		fontSize: '32rpx',
		fontWeight: '600'
	};

	onMounted(async () => {
		const httpUrl = uni.getStorageSync("HTTP");
		noneGoodsImageUrl.value = httpUrl + '/static/none.png';
		
		// 获取主题色
		mainColor.value = getCSSVariable('--mainColor', '#6bb7ec');
		
		await funcationS();
		EventBus.on('shopClientInfo', (objParam) => {
			doGetShopping();
		});

		const titleColor = getCSSVariable('--titleColor', '#333333');
		console.log('获取到的titleColor:', titleColor);
	})

	const funcationS = async () => {
		await doGetShopping();
		await doGetShoppingCount();
	}

	const imgerror = (index, indexDetails) => {
		console.log(noneGoodsImageUrl.value);
		if (shoppingCartData.length > 0) {
			shoppingCartData[index].details[indexDetails].imgurl = noneGoodsImageUrl.value;
		}
	}

	const isShowNoData = ref(false);
	let shoppingCartData = reactive([]);

	const doTurnAround = () => {
		uni.setStorageSync("index", 1);
		uni.navigateTo({
			url: '/pages/index/index'
		});
	}

	const paging = ref(null);
	const doGetShopping = async () => {
		shoppingCartData.length = 0;
		let tempShoppingCartData = [];
		let convertShoppingCartData = [];
		let params = {};
		params["P_PROC_NAME"] = procName;
		params["P_ACTION"] = "QUERYALL";
		await postCall(params).then(res => {
			if (res) {
				if (res.code === 200) {
					Object.assign(tempShoppingCartData, res.data.DATASET);

					const mergedData = tempShoppingCartData.reduce((acc, cur) => {
						const { businesscode, businessid, businessname, recemanid, recemanname, addressid, address, recetelephone, staffid, ...rest } = cur;
						if (!acc[businesscode]) {
							acc[businesscode] = { businesscode, businessid, businessname, recemanid, recemanname, addressid, address, recetelephone, staffid, details: [rest] };
						} else {
							acc[businesscode].details.push(rest);
						}
						return acc;
					}, {});

					const businessStats = {};
					for (const key in mergedData) {
						const business = mergedData[key];
						const totalPrice = business.details.reduce((total, item) => (new Big(total).plus(new Big(item.taxamount))), 0);
						mergedData[key]["taxamount"] = totalPrice;
					}
					for (const key in mergedData) {
						if (Object.hasOwnProperty.call(mergedData, key)) {
							convertShoppingCartData.push(mergedData[key]);
						}
					}
					Object.assign(shoppingCartData, convertShoppingCartData);
				}
			}
		})
	}

	const modalRef = ref()

	const handleClick = () => {
		console.log(111);
	}

	const hideModal = () => {
		console.log(222);
	}

	const doDelShopping = async (val, index) => {
		modalRef.value?.showModal({
			title: '确认删除',
			content: '确定要删除该店铺的所有商品吗？',
			showCancel: true,
			cancel: () => {

			},
			confirm: () => {
				console.log(val + "--" + index)
				let params = {};
				params["P_PROC_NAME"] = procName;
				params["P_ACTION"] = "DELETEALL";
				params["P_CLIENTID"] = val;

				postCall(params).then(res => {
					if (res) {
						if (res.code === 200) {
							toastMessage("删除成功！");
							shoppingCartData.splice(index, 1);
							doGetShoppingCount();
						}
					}
				})
			},
		})
	}

	let doGetShoppingCount = async () => {
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_SHOPPING";
		params["P_ACTION"] = "QUERYALLCOUNT";
		await postCall(params).then(res => {
			if (res) {
				if (res.code === 200) {
					if (res.data.DATASET.length > 0) {
						store.state.shopingBadge = res.data.DATASET[0].sumcount;
					}
				}
			}
		})
	}

	let toNavigate = (val) => {
		uni.setStorageSync("SHOPCLIENTINFO", val);
		uni.navigateTo({
			url: '/pages/shop/shopdetails'
		})
	}
</script>

<style scoped>
.shop-container {
	min-height: 100vh;
	background: linear-gradient(to bottom, #f8f9ff 0%, #f0f2f9 100%);
}

/* 头部样式 */
.header-section {
	background-color: var(--tn-color-primary);
	position: relative;
	box-shadow: 0 4rpx 20rpx rgba(var(--tn-color-primary-rgb), 0.15);
}

.header-content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 32rpx 40rpx;
}

.header-title {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.title-text {
	font-size: 36rpx;
	font-weight: 700;
	color: var(--tn-color-white, #ffffff);
	letter-spacing: 1rpx;
}

.cart-badge {
	background: rgba(255, 255, 255, 0.2);
	color: var(--tn-color-white, #ffffff);
	font-size: 24rpx;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

/* 空状态样式 */
.empty-state {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 60vh;
	padding: 40rpx;
}

.empty-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
}

.empty-icon {
	margin-bottom: 40rpx;
	opacity: 0.6;
}

.empty-text {
	margin-bottom: 60rpx;
}

.empty-title {
	display: block;
	font-size: 36rpx;
	font-weight: 600;
	color: var(--tn-color-black, #333);
	margin-bottom: 16rpx;
}

.empty-subtitle {
	display: block;
	font-size: 28rpx;
	color: var(--tn-color-gray, #666);
	line-height: 1.5;
}

.shop-now-btn {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 0 48rpx !important;
	border-radius: 44rpx !important;
	transition: all 0.3s ease;
}

.shop-now-btn:active {
	transform: translateY(2rpx);
}

.btn-text {
	font-size: 32rpx;
	font-weight: 600;
	color: var(--tn-color-white, #ffffff);
}

/* 商品列表样式 */
.cart-list {
	padding: 32rpx 24rpx;
	padding-bottom: 120rpx;
}

.merchant-card {
	background: #ffffff;
	border-radius: 24rpx;
	margin-bottom: 24rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	transition: all 0.3s ease;
}

.merchant-card:active {
	transform: translateY(2rpx);
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.12);
}

.merchant-header {
	padding: 24rpx 32rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid #f5f5f5;
	background: linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%);
}

.merchant-info {
	display: flex;
	align-items: center;
	gap: 20rpx;
	flex: 1;
}

.merchant-icon {
	width: 56rpx;
	height: 56rpx;
	background: rgba(var(--tn-color-primary-rgb, 107, 183, 236), 0.1);
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1rpx solid rgba(var(--tn-color-primary-rgb, 107, 183, 236), 0.2);
}

.merchant-details {
	flex: 1;
}

.merchant-name {
	display: block;
	font-size: 32rpx;
	font-weight: 600;
	color: var(--tn-color-black, #333);
	margin-bottom: 8rpx;
	max-width: 300rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.merchant-stats {
	display: block;
	font-size: 24rpx;
	color: var(--tn-color-gray, #666);
}

.merchant-actions {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.total-price {
	display: flex;
	align-items: baseline;
	gap: 4rpx;
}

.currency {
	font-size: 24rpx;
	color: var(--tn-color-red, #ff6b6b);
	font-weight: 500;
}

.amount {
	font-size: 36rpx;
	font-weight: 700;
	color: var(--tn-color-red, #ff6b6b);
}

.action-buttons {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.delete-btn {
	width: 56rpx;
	height: 56rpx;
	background: #fff5f5;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
	border: 1rpx solid #ffd6d6;
}

.delete-btn:active {
	background: #ffe0e0;
	transform: scale(0.95);
}

.arrow-btn {
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 商品网格样式 */
.products-grid {
	padding: 24rpx 32rpx 32rpx;
}

.grid-container {
	display: grid;
	grid-template-columns: repeat(5, 1fr);
	gap: 12rpx;
}

.product-item {
	position: relative;
	aspect-ratio: 1;
	border-radius: 8rpx;
	overflow: hidden;
	background: #f8f9fa;
	border: 1rpx solid #eee;
}

.product-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
	transition: all 0.3s ease;
}

.product-item:active .product-image {
	transform: scale(1.05);
}

.more-products {
	position: relative;
	aspect-ratio: 1;
	border-radius: 8rpx;
	background: linear-gradient(135deg, #f0f2f9 0%, #e5e7eb 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1rpx dashed #ccc;
}

.more-text {
	font-size: 20rpx;
	color: var(--tn-color-gray, #666);
	font-weight: 600;
}

/* 底部安全区域 */
.safe-area-bottom {
	height: env(safe-area-inset-bottom);
	background: transparent;
}

/* 响应式优化 */
@media (max-width: 750rpx) {
	.grid-container {
		grid-template-columns: repeat(4, 1fr);
		gap: 10rpx;
	}
	
	.merchant-header {
		padding: 24rpx;
	}
	
	.products-grid {
		padding: 20rpx 24rpx 24rpx;
	}
}

@media (max-width: 600rpx) {
	.grid-container {
		grid-template-columns: repeat(3, 1fr);
		gap: 8rpx;
	}
}

/* 动画效果 */
@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(30rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.merchant-card {
	animation: fadeInUp 0.5s ease forwards;
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
	.shop-container {
		background: linear-gradient(to bottom, #1a1a2e 0%, #16213e 100%);
	}
	
	.merchant-card {
		background: #2a2a3e;
		border: 1rpx solid #333;
	}
	
	.merchant-name {
		color: #ffffff;
	}
	
	.merchant-stats {
		color: #ccc;
	}
}
</style>
